package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }
    
    /**
     * 查出所有分类,并设置自己的子节点
     * @return
     */
    @Override
    public List<CategoryEntity> listTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> collect = categoryEntities.stream().map(item->{
            item.setChildren(getChildrens(item,categoryEntities));
            return item;
        }).filter(item->item.getParentCid()==0).sorted((item1,item2)->{
            return (item1.getSort()== null?0:item1.getSort()) - (item2.getSort()==null?0:item2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void removeMenusByIds(Long[] catIds) {
        // @TODO 1、查询哪些catIds被引用，被引用的不能够被删除
        baseMapper.deleteBatchIds(Arrays.asList(catIds));
    }

    /**
     * 递归获取当前菜单的子菜单
     * @param root  当前菜单
     * @param list  菜单集合
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> list){
        List<CategoryEntity> childrens =
            list.stream()
                .filter(item -> item.getParentCid().longValue()== root.getCatId())
                .map(
                    item -> {
                      item.setChildren(getChildrens(item, list));
                      return item;
                    })
                .sorted(
                    (item1, item2) -> {
                      System.out.println("item="+item1 +",item2="+item2);
                      // 菜单排序
                      return (item1.getSort() == null ? 0 : item1.getSort())
                          - (item2.getSort() == null ? 0 : item2.getSort());
                    })
                .collect(Collectors.toList());
        return childrens;
    }

    public List<CategoryEntity> setChildrens(CategoryEntity root,List<CategoryEntity> list){
        List<CategoryEntity> collect = list.stream().filter(item ->
                item.getParentCid() == root.getCatId()
        ).collect(Collectors.toList());
        List<CategoryEntity> collect1 = collect.stream().map(item -> {
            item.setChildren(setChildrens(item, list));
            return item;
        }).collect(Collectors.toList());
        return collect1;
    }
    public void setChildrens(List<CategoryEntity> list){
        list.stream().map(item->{
            item.setChildren(setChildrens(item,list));
            return item;
        });
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        // parentPath.toArray(new Long[parentPath.size()]) 表示将parentPath 的集合转成 Long 类型的数组，他跟parentPath.toArray()的
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @Override
    @Transactional
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }
}
